package com.example.demo;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;


import com.example.demo.API.JokeEntity;
import com.example.demo.API.JokeService;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitDemoActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_retrofit_demo);

        RecyclerView recyclerView = findViewById(R.id.recycler_view);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(manager);
        JokeAdapter adapter = new JokeAdapter(this);
        recyclerView.setAdapter(adapter);

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://autumnfish.cn/api/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        JokeService service = retrofit.create(JokeService.class);

        Call<JokeEntity> call = service.getJokes(10);

        // 同步 & 异步
        // ANR
        // 异步请求

        call.enqueue(new Callback<JokeEntity>() {
            @Override
            public void onResponse(Call<JokeEntity> call, Response<JokeEntity> response) {
                JokeEntity entity = response.body();
                adapter.setData(entity.getJokes());
            }

            @Override
            public void onFailure(Call<JokeEntity> call, Throwable t) {
                t.printStackTrace();
            }
        });
    }
}